<?php
class Weixin {
    public $errorMsg = array();
    public $response = array();
    public $token;
    private $cache;

    public function __construct() {
        $this->cache = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.'weixin.token';
        !file_exists($this->cache) && touch($this->cache);
        $this->token = file_get_contents($this->cache);
    }

    public function login(){
        $response = Weixin::ajax(
            "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".WEIXIN_CORP_ID."&corpsecret=".WEIXIN_CORP_SECRET,
            'GET'
        );
        $response = json_decode($response, true);
        $this->response[] = $response;
        if (!empty($response['access_token'])) {
            file_put_contents($this->cache, $response['access_token']);
            return $response['access_token'];
        } else {
            $this->errorMsg[] = $response['errmsg'];
            return false;
        }
    }

    public function sendText($textContent) {
        $retry=3;
        while($retry--) {
            $response = Weixin::ajax(
                "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$this->token,
                'POST',
                array(
                    "touser" => "@all", "msgtype" => 'text', 'agentid' => "1",
                    "text" => array("content" => $textContent),
                )
            );
            $response = json_decode($response, true);
            $this->response[] = $response;
            if ($response['errcode'] == 0) {
                return true;
            // 40014 invalid access_token
            // 41001 access_token missing
            } elseif (in_array($response['errcode'], array(40014, 41001))) {
                $this->token = $this->login();
            } else {
                $this->errorMsg[] = $response['errmsg'];
                return false;
            }
        };
        return false;
    }

    private static function ajax($url, $method = 'POST', $params = array()){
        $c = curl_init($url);
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        if ($method == 'POST') {
            $paramsJson = json_encode($params, JSON_UNESCAPED_UNICODE);
            curl_setopt($c, CURLOPT_POSTFIELDS, $paramsJson);
            curl_setopt($c, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: '.strlen($paramsJson))
            );
        }
        $s = curl_exec($c);
        curl_close($c);
        return $s;
    }
};
